package com.xiaodeng.xdblogspringboot.interceptors;

import cn.hutool.core.util.StrUtil;
import com.xiaodeng.xdblogspringboot.exception.UserException;
import com.xiaodeng.xdblogspringboot.utils.JwtUtil;
import com.xiaodeng.xdblogspringboot.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.xiaodeng.xdblogspringboot.constant.RedisConstants.USER_TOKEN;


@Component
public class GlobalInterceptor extends ServiceInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的 token
        String token = request.getHeader("Authorization");
        // 如果 token 为空，直接放行
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 从 Redis 中获取 token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");
        String userKey = USER_TOKEN + username; // 确保 parseToken 返回用户名
        String redisToken = operations.get(userKey);

        // 检查 token 是否失效或不匹配
        if (redisToken == null || !redisToken.equals(token)) {
            return true; // token 失效或不匹配，直接放行
        }
        // 将业务数据存储到 ThreadLocal 中
        ThreadLocalUtil.set(claims);
        // 刷新 Redis 中的 token 有效期
        stringRedisTemplate.expire(userKey, 4, TimeUnit.DAYS);
        // 放行
        return true;
    }
}
